package com.laboratory.exception;

import com.laboratory.domain.ResponseCode;
import com.laboratory.domain.ResponseResult;
import jakarta.validation.ConstraintViolationException;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.LinkedHashMap;
import java.util.Map;

@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 处理 MethodArgumentNotValidException （JSON参数校验失败）
     *
     * @param e
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseResult handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        Map<String, String> errors = new LinkedHashMap<>();
        e.getBindingResult().getFieldErrors().forEach(
                error -> errors.putIfAbsent(error.getField(), error.getDefaultMessage())
        );
        return new ResponseResult(
                ResponseCode.GET_ERROR,
                ExceptionDescription.methodArgumentNotValidException,
                errors
        );
    }

    /**
     * 处理 BindException （表单参数校验失败）
     *
     * @param e
     * @return
     */
    @ExceptionHandler(BindException.class)
    public ResponseResult handleBindException(BindException e) {
        Map<String, String> errors = new LinkedHashMap<>();
        e.getBindingResult().getFieldErrors().forEach(
                error -> errors.putIfAbsent(error.getField(), error.getDefaultMessage())
        );
        return new ResponseResult(
                ResponseCode.GET_ERROR,
                ExceptionDescription.bindException,
                errors
        );
    }

    /**
     * 处理 ConstraintViolationException （方法参数校验失败）
     *
     * @param e
     * @return
     */
    @ExceptionHandler(ConstraintViolationException.class)
    public ResponseResult handleConstraintViolationException(ConstraintViolationException e) {
        Map<String, String> errors = new LinkedHashMap<>();
        e.getConstraintViolations().forEach(
                v -> {
                    String path = v.getPropertyPath() == null ? "" : v.getPropertyPath().toString();
                    errors.put(path, v.getMessage());
                });
        return new ResponseResult(
                ResponseCode.GET_ERROR,
                ExceptionDescription.constraintViolationException,
                errors
        );
    }

}
